import { Game, GameComponent } from "@sapi-game/main";
import { PixelPartyMainState } from "../states/mainState";
import { SphereRegion } from "@sapi-game/gameRegion/gameRegion";
import { DimensionIds } from "@sapi-game/utils/vanila-data";
import { RegionEventType } from "@sapi-game/gameEvent/events/regionEvents";
import { GameMode } from "@minecraft/server";

export class PixelPartyRelife extends GameComponent<PixelPartyMainState> {
    override onAttach(): void {
        this.subscribe(
            Game.events.region,
            (t) => {
                if (t.type != RegionEventType.Enter) return;
                const gamePlayer = this.context.players.getById(t.player.id);
                if (!gamePlayer) return;
                if (gamePlayer.relifeTimes > 0 && !gamePlayer.isRelife) {
                    gamePlayer.isRelife = true;
                    gamePlayer.relifeTimes--;
                    gamePlayer.sendMessage(
                        `你将在下回合复活(剩余复活次数${gamePlayer.relifeTimes})`
                    );
                }
            },
            new SphereRegion(
                DimensionIds.Overworld,
                { x: 114.5, y: -56.5, z: -161.5 },
                5
            )
        );
    }

    relifeAll() {
        let relifeCnt = 0;
        this.context.players.forEach((p) => {
            if (p.isRelife) {
                p.player.teleport(this.context.map.spawnPoint);
                p.player.setGameMode(GameMode.Adventure);
                p.alive = true;
                relifeCnt++;
                p.isRelife = false;
            }
        });
        if (relifeCnt)
            this.context.players.sendMessage(`§a本局${relifeCnt}名玩家复活了`);
    }
}
